

package cn.iocoder.yudao.core.sensitive;

import cn.iocoder.yudao.core.sensitive.annotation.FieldSensitive;
import cn.iocoder.yudao.core.sensitive.stragegy.ISensitiveStrategy;
import cn.iocoder.yudao.core.sensitive.stragegy.SensitiveStrategy;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Objects;

@NoArgsConstructor
@AllArgsConstructor
public class SensitiveInfoSerialize extends JsonSerializer<String> implements ContextualSerializer {
    private static ISensitiveStrategy SENSITIVE_STRATEGY = new SensitiveStrategy();
    private String type;
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeObject(SENSITIVE_STRATEGY.handle(this.type, value));
    }
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (null != property) {
            if (Objects.equals(property.getType().getRawClass(), String.class)) {
                FieldSensitive sensitiveInfo = property.getAnnotation(FieldSensitive.class);
                if (null == sensitiveInfo) {
                    sensitiveInfo = property.getContextAnnotation(FieldSensitive.class);
                }

                if (null != sensitiveInfo) {
                    return new SensitiveInfoSerialize(sensitiveInfo.type());
                }
            }

            return prov.findValueSerializer(property.getType(), property);
        } else {
            return prov.findNullValueSerializer(null);
        }
    }

    public static void setSensitiveStrategy(ISensitiveStrategy sensitiveStrategy) {
        SENSITIVE_STRATEGY = sensitiveStrategy;
    }
}
